//
//  HomeViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/6/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "HomeViewController.h"
#import "CategoryViewController.h"
#import "ProductDetailViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize mainView, productArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    [self getAllProducts];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeUserStatus) name:@"ChangedUserStatus" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
    if (!isConnected) {
        [self getAllProducts];
    }
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];    
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}


- (void)viewDidUnload {
    [self setMainView:nil];
    [self setTableView:nil];
    [super viewDidUnload];
}

- (IBAction)searchButtonPressed:(id)sender {
    isFromHome = YES;
    [self.tabBarController setSelectedIndex:1];
}

- (void)getAllProducts{
    NSString *path = [NSString stringWithFormat:@"%@/get_all_product",serverPath];
    NSURL *url = [NSURL URLWithString:path];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
}

-(void)changeUserStatus{
    if (isLogin) {
        NSString *userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
        userData = [[NSDictionary alloc]initWithContentsOfFile:userInfoPath];
    }else{
        userData = nil;
    }
    [self.tableView reloadData];
}

#pragma mark ASIHTTPRequest Delegates
//For Asynchronous Request
- (void)requestFailed:(ASIHTTPRequest *)request{
//    UIAlertView *alert= [[UIAlertView alloc]initWithTitle:@"Network Error" message:@"The Internet connection appears to be offline" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
//    [alert show];
    isConnected = NO;
}

//For Asynchronous Request
- (void)requestFinished:(ASIHTTPRequest *)request{
    NSData *responseData = [request responseData];
    JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
    productArray = [jsonDecoder objectWithData:responseData];
    isConnected = YES;
    [self.tableView reloadData];
}

#pragma mark -
#pragma Table View Data Source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger row = [indexPath row];
    if (row == 1) {
        return 90.0f;
    }else if (row == 2){
        return 252.0f;
    }else{
        return 40.0f;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSUInteger row = [indexPath row];
        switch (row) {
            case 0:{
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShopByDepartment"];
                cell.textLabel.text = @"Shop by Department";
                cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
                cell.textLabel.textColor = [UIColor colorWithRed:255/255.0 green:153/255.0 blue:0/255.0 alpha:1];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                return cell;
            }
            case 1:{
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DealCell"];
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, 80)];
                [imageView setImage:[UIImage imageNamed:@"amazing-deal.png"]];
                [imageView setContentMode:UIViewContentModeScaleAspectFit];
                [cell addSubview:imageView];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
                
            case 2:{
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ScrollViewCell"];
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(cell.frame.origin.x + 10, cell.frame.origin.y, cell.frame.size.width, 30)];
                label.font = [UIFont fontWithName:@"Helvetica" size:15.0];
                label.textColor = [UIColor colorWithRed:255/255.0 green:153/255.0 blue:0/255.0 alpha:1];
                label.text = @"The most viewed items";
                
                UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y + 40, cell.frame.size.width, 220.0f)];
                scrollView.showsHorizontalScrollIndicator = NO;
                for (NSInteger i = 0; i < productArray.count; i++) {
                    ScrollViewCell *productViewCell = [[ScrollViewCell alloc]initWithFrame:CGRectMake(180*i, 0, 180, 200)];
                    [productViewCell setImagePath: [[[productArray objectAtIndex:i] valueForKey:@"product_images"] objectAtIndex:0]];
                    [productViewCell setName: [[productArray objectAtIndex:i] valueForKey:@"product_name"]];
                    [productViewCell setProductID: (NSInteger *)[[[productArray objectAtIndex:i] valueForKey:@"product_id"] intValue]];
                    [productViewCell setPrice: [[productArray objectAtIndex:i] valueForKey:@"product_price"]];
                    [productViewCell setDelegate:self];
                    [scrollView addSubview:productViewCell];
                    productViewCell = nil;
                }
                
                CGFloat scrollViewHeight = 220.0f;
                CGFloat scrollViewWidth = 0.0f;
                for (UIView *view in scrollView.subviews)
                {
                    scrollViewWidth += view.frame.size.width;
                }
                [scrollView setContentSize:(CGSizeMake(scrollViewWidth, scrollViewHeight))];
                [cell.contentView addSubview:label];
                [cell.contentView addSubview:scrollView];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return  cell;
            }
                
            case 3:{
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UserLogging"];
                if (isLogin) {
                    cell.textLabel.text = [NSString stringWithFormat:@"Hello, %@", [userData valueForKey:@"Name"]];
                    cell.detailTextLabel.text = @"Sign Out";
                }else{
                    cell.textLabel.text = @"Already a customer?";
                    cell.detailTextLabel.text = @"Sign In";
                }
                
                cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
                cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
                cell.textLabel.textColor = [UIColor colorWithRed:255/255.0 green:153/255.0 blue:0/255.0 alpha:1];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.backgroundColor = [UIColor blackColor];
                return cell;
            }
                
            default:{
                return nil;
            }
        }
}

#pragma mark Table View Delegates

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger row = [indexPath row];
    switch (row) {
        case 0:{
            CategoryViewController *nextController = [[CategoryViewController alloc]init];
            nextController.navigationItem.title = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
            [self.navigationController pushViewController:nextController animated:YES];
            nextController = nil;
        }
            break;
            
        case 1:{
            
        }
            break;
            
        case 3:{
            LoginViewController *nextController = [[LoginViewController alloc]init];
            nextController.navigationItem.title = [tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text;
            [self.navigationController pushViewController:nextController animated:YES];
            nextController = nil;
        }
            break;
                        
        default:
            break;
    }
}

#pragma mark ScrollViewCell Delegate
-(void)didSelectProduct:(NSInteger *)pid{
    ProductDetailViewController *nextController = [[ProductDetailViewController alloc]init];
    [nextController setProductID:pid];
    [self.navigationController pushViewController:nextController animated:YES];
    nextController = nil;
}

@end
